package servlets;

import business.SM;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.List;
import java.util.Iterator;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author hugo
 * @version
 */
public class UploadFile extends HttpServlet {

    private String dirUploadFiles;


    protected int processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        //Obtengo el directorio donde guardar desde un parametro de contexto en el archivo web.xml
        //dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
        String namePROP = SM.class.getSimpleName().toLowerCase() + ".properties";
        Properties props = new Properties();
        props.load(SM.class.getResourceAsStream(namePROP));
        dirUploadFiles = props.getProperty("path");        
        

        if (ServletFileUpload.isMultipartContent(request))
        {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            //upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue()); // 1024 x 300 = 307200 bytes = 300 Kb

            List listUploadFiles = null;
            FileItem item = null;

            try
            {
                listUploadFiles = upload.parseRequest(request);

                Iterator it = listUploadFiles.iterator();
                while (it.hasNext())
                {
                    item = (FileItem) it.next();
                    if (!item.isFormField() && item.getSize() > 0)
                    {
                        //Comprobamos que en la carpeta de destino no exista ya un fichero con el mismo nombre que estamos subiendo
                        File f = new File(dirUploadFiles, item.getName());
                        if(f.exists())
                        {
                            response.sendRedirect("adminWeb/admin.jsp?exists");
                            return 2;
                        }
                        else
                        {
                            //Creamos un fichero temporal para que el Tomcat pueda acceder a el                            
                            File tempFile = new File(System.getProperty("user.dir")+ "\\..\\temp\\", item.getName());
                            item.write(tempFile);
                            while(!tempFile.exists())
                            {
                                ;
                            }

                            //Y otro para que el usuario tenga constancia de que se ha subido
                            FileInputStream in = new FileInputStream(tempFile);
                            FileOutputStream file = new FileOutputStream(dirUploadFiles+"\\"+item.getName());
                            
                            int c;
                            while( (c = in.read() ) != -1)
				file.write(c);
                            in.close();
                            file.close();
                            /*if (tempFile.exists() && file. exists())
                            {*/
                                response.sendRedirect("adminWeb/admin.jsp?fileName=" + item.getName() + "&path="+ dirUploadFiles);
                                return 0;
                            /*}
                            else
                                return 1;*/
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return -1;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
